package com.czn.service.impl;

import com.czn.dao.DoctorDao;
import com.czn.dao.PatientDao;
import com.czn.dao.UserDao;
import com.czn.entity.Doctor;
import com.czn.entity.Patient;
import com.czn.entity.User;
import com.czn.service.IUserService;
import com.czn.vo.ActiveUser;
import com.czn.vo.ResponseResult;
import org.beetl.sql.core.engine.PageQuery;
import org.beetl.sql.core.query.LambdaQuery;
import org.beetl.sql.core.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;

/**
 * @author ChenZeNan
 * @create 2021-04-14 19:16
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private PatientDao patientDao;

    @Autowired
    private DoctorDao doctorDao;

    /**
     * 用户登录
     *
     * @param user
     * @param session
     * @return
     */
    @Override
    public ResponseResult checkUser(User user, HttpSession session) {
        // 查询到的用户
        User sysUser = userDao.findUserByUsername(user.getUsername());
        ResponseResult result = new ResponseResult();
        if (sysUser == null) { // 用户不存在
            result.setCode("101"); // 101 代表用户不存在
            result.setMessage("用户不存在~");
        } else {
            if (!sysUser.getPassword().equals(user.getPassword())) { // 密码错误
                result.setCode("102"); // 102 代表密码错误
                result.setMessage("密码错误~");
            } else {
                result.setCode("100"); // 100 代表验证通过
                result.setMessage(String.valueOf(sysUser.getRole())); // 传递用户的角色信息
                session.setAttribute("user", sysUser); // 将用户存入sessino域
            }
        }
        return result;
    }

    /**
     * 用户注册
     *
     * @param activeUser
     * @return
     */
    @Override
    public ResponseResult registUser(ActiveUser activeUser) {
        // 根据注册信息中的用户名查询用户是否已存在
        User sysUser = userDao.findUserByUsername(activeUser.getUsername());
        ResponseResult result = new ResponseResult();

        if (activeUser.getCertId().isEmpty()) {
            result.setCode("201");
            result.setMessage("请输入身份证！");
            return result;
        } else if (activeUser.getUsername().isEmpty()) {
            result.setCode("202");
            result.setMessage("请输入用户名");
            return result;
        } else if (activeUser.getPassword().isEmpty()) {
            result.setCode("203");
            result.setMessage("请输入密码！");
            return result;
        } else if (sysUser != null) {
            result.setCode("204");
            result.setMessage("用户已存在！");
            return result;
        } else {
            sysUser = new User();
            sysUser.setUsername(activeUser.getUsername());
            sysUser.setPassword(activeUser.getPassword());
            // 根据身份证查询患者
            Query<Patient> patientQuery = patientDao.createQuery();
            patientQuery.andEq("cert_id", activeUser.getCertId());
            Patient patient = patientQuery.single();
            if (patient != null && patient.getUserId() == null) {  // 说明要注册的人是患者
                sysUser.setRole(3);
                userDao.insert(sysUser);
                // 更新患者表
                patient.setUserId(userDao.findUserByUsername(sysUser.getUsername()).getId());
                patientDao.updateById(patient);
                result.setCode("200");
                result.setMessage("患者注册成功!");
                return result;
            }
            // 根据身份证查询医生
            Query<Doctor> doctorQuery = doctorDao.createQuery();
            doctorQuery.andEq("cert_id", activeUser.getCertId());
            Doctor doctor = doctorQuery.single();
            if (doctor != null && doctor.getUserId() == null) {  // 说明要注册的人是医生
                sysUser.setRole(2);
                userDao.insert(sysUser);
                // 更新医生表
                doctor.setUserId(userDao.findUserByUsername(sysUser.getUsername()).getId());
                doctorDao.updateById(doctor);
                result.setCode("200");
                result.setMessage("医生注册成功!");
                return result;
            }
            result.setCode("205");
            result.setMessage("身份证为认证或已被注册，请联系管理员~");

        }
        return result;
    }

    /**
     * 分页/模糊查询管理员
     *
     * @param pageNo
     * @param pageSize
     * @param username
     * @return
     */
    @Override
    public PageQuery<User> findUserList(Integer pageNo, Integer pageSize, String username) {
        LambdaQuery<User> query = userDao.createLambdaQuery();
        if (!StringUtils.isEmpty(username)) {
            query.andLike(User::getUsername, "%" + username + "%");
        }
        query.andEq(User::getRole, "1");
        if (pageNo > 0 && pageSize > 0) {
            PageQuery<User> page = query.desc(User::getId).page(pageNo, pageSize);
            return page;
        }
        return null;
    }

    /**
     * 添加管理员
     *
     * @param user
     * @return
     */
    @Override
    public ResponseResult addUser(User user) {
        ResponseResult result = new ResponseResult();
        // 根据身份证查询数据库中是否已有该对象了
        LambdaQuery<User> query = userDao.createLambdaQuery();
        query.andEq(User::getUsername, user.getUsername());
        query.andEq(User::getRole, 1);
        User sysUser = query.single();
        if (sysUser == null) { // 数据库中没有该对象，直接插入
            user.setRole(1);
            userDao.insert(user);
            result.setCode("300");
            result.setMessage("信息添加成功！");
            return result;
        }
        // 数据库中已有该对象了
        result.setCode("301");
        result.setMessage("该账号已经被注册~");
        return result;
    }

    /**
     * 编辑管理员
     *
     * @param user
     * @return
     */
    @Override
    public ResponseResult editUser(User user) {
        ResponseResult result = new ResponseResult();
        user.setRole(1);
        int rows = userDao.updateById(user);
        if (rows > 0) {
            result.setCode("500");
            result.setMessage("信息更新成功！");
            return result;
        }
        result.setCode("501");
        result.setMessage("信息更新失败！");
        return result;
    }

    /**
     * 根据id查找管理员
     *
     * @param id
     * @return
     */
    @Override
    public User findUserById(Integer id) {
        User user = userDao.single(id);
        return user;
    }

    /**
     * 根据id删除管理员
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteUserById(Integer id) {
        ResponseResult result = new ResponseResult();
        int rows = userDao.deleteById(id);
        if (rows > 0) {
            result.setCode("400");
            result.setMessage("删除成功！");
            return result;
        }
        result.setCode("401");
        result.setMessage("删除失败！");
        return result;
    }
}
